#!/usr/binenv python
import sys
import numpy
import math

def big_x(x):
    if x > 0:
        return 1.0
    else:
        return 0.0

def logit(x):
    if abs(x) > 100:
        return big_x(x)

    return 1.0 / (1.0 - math.exp(-x))

def main():
    if len(sys.argv) < 4:
        sys.stderr.write('%s <train> <train_answers> <test>' % (sys.argv[0]))
        exit(1)

    train_path          =   sys.argv[1]
    train_answers_path  =   sys.argv[2]
    test_path           =   sys.argv[3]

    plus_amplification  =   1.1
    minus_amplification =   1.0


    weigths =   list()
    answers =   list()
    with open(train_answers_path, 'r') as train_answers_file:
        for x in train_answers_file:
            value   =   int(x)
            if value == -1:
                value   =   0

            answers.append(value)

            weigth  =   minus_amplification
            if value == 1:
                weigth  =   plus_amplification

            weigths.append(weigth)

    examples    =   list()
    with open(train_path, 'r') as train_file:
        for line_num, line in enumerate(train_file):
            example =   [float(x) for x in line.split(' ')]
            """free member"""
            example.append(1.0)
            example =   numpy.array(example, numpy.float)
            examples.append(example)

    teta            =   numpy.ones(len(examples[0]), numpy.float)
    dteta           =   numpy.ones(len(examples[0]), numpy.float)
    epsilon         =   8.5
    alpha           =   0.1
    f               =   logit
    progress        =   0

    df          =   numpy.ones(len(examples), numpy.float)
    df_l2       =   epsilon + 1
    df_l2_min   =   df_l2
    while df_l2 > epsilon:
        if progress % 100 == 0:
            sys.stderr.write('%d iterations passed, df_l2_min = %f\n' % ( progress
                                                                        , df_l2_min ))
            df_l2_min   =   100000
        progress    +=  1
        for example_num, example in enumerate(examples):
            df[example_num] =   weigths[example_num] * (answers[example_num] - f(numpy.dot(teta, example)))
            dteta           +=  alpha * df[example_num] * example
        df_l2           =   math.sqrt(numpy.dot(df, df))
        df_l2_min       =   min(df_l2_min, df_l2)
        teta            +=  dteta


    with open(test_path, 'r') as test_file:
        for line in test_file:
            example =   [float(x) for x in line.split(' ')]
            """free member"""
            example.append(1.0)
            result  =   f(numpy.dot(example, teta))
            if result >= 0.5:
                result  =   1
            else:
                result  =   -1
            print result

if __name__ == "__main__":
    main()
